package util;

import java.io.UnsupportedEncodingException;

public class ByteBuffer
{
	static final int SIZE = 32;
	// 内容
	byte[] bytes;
	// 读取位置
	int read;
	// 写入位置
	int write;

	public ByteBuffer()
	{
		bytes = new byte[SIZE];
	}

	/** 扩容 */
	public void setCapacity(int size)
	{
		if (bytes.length > size) {
			return;
		}
		byte[] temp = new byte[size];
		System.arraycopy(bytes, 0, temp, 0, write);
		bytes = temp;
	}

	/**剩余可读字节数*/
	public int remaining()
	{
		return bytes.length - read;
	}

	public byte[] getBytes()
    {
	    return bytes;
    }
	
	/**获得有效字节数*/
	public int getEffective()
    {
	    return write;
    }

	public void clear() 
	{
		read = 0;
		write = 0;
	}
	

	public void writeBytes(byte[] bytes2, int index, int end)
    {
		int size = end - index;
		if (bytes.length < write + size) {
			setCapacity(write + SIZE);
		}
	    for(int i=0;i<size;i++)
	    {
	    	bytes[write + i] = bytes2[i];
	    }
	    write += size;
    }

	public void writeInt(int i)
	{
		int size = 4;
		if (bytes.length < write + size) {
			setCapacity(write + SIZE);
		}
		for (int j = 0; j < size; j++) {
			bytes[write + j] = (byte) (i >>> 8 * (size - 1 - j));
		}
		write += size;
	}

	public int readInt()
	{
		int size = 4;
		int value = 0;
		for (int j = 0; j < size; j++) {
			value += (bytes[read+j]&0xff) << 8 * (size - 1 - j);
		}
		this.read+=size;
		return value;
	}
	
	public void writeUTF(String str)
	{
		try {
			byte[] b = str.getBytes("utf8");
			
			writeBytes(b, 0, b.length);
			write += b.length;
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public String readUTF()
	{
		try {
			int len = readInt();
			
			String str = new String(bytes,read,len,"utf8");
			read += len;
			return str;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}

}
